package com.yinuo.face.user;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v8.renderscript.RenderScript;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.arcsoft.facerecognition.AFR_FSDKFace;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.SnackbarUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.orhanobut.logger.Logger;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.ModelAdapter;
import com.ufo.imageselector.DWImages;
import com.yinuo.face.ArcSdkEngine;
import com.yinuo.face.R;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import cc.cloudist.acplibrary.ACProgressConstant;
import cc.cloudist.acplibrary.ACProgressFlower;
import io.github.silvaren.easyrs.tools.Nv21Image;

public class UserListActivity extends AppCompatActivity {

    private final String USER_HEADER_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/face/user/";
    private final List<User> USER_LIST = new ArrayList<>();
    private final List<Rect> FACE_RECT_LIST = new ArrayList<>();
    private Handler handler = new Handler();
    private RenderScript rs;
    private ModelAdapter<User> userModelAdapter;
    private UserListAdapter adapter;
    private TwinklingRefreshLayout refreshLayout;
    private RefreshListenerAdapter refreshListener = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    reload(0);
                    refreshLayout.finishRefreshing();
                }
            }, 500);
        }

        @Override
        public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    reload(USER_LIST.size());
                    refreshLayout.finishLoadmore();
                }
            }, 500);
        }
    };
    private BaseQuickAdapter.OnItemClickListener onItemClickListener = new BaseQuickAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            User user = (User) adapter.getItem(position);

            Intent intent = new Intent(UserListActivity.this, UserActivity.class);
            intent.putExtra("userId", user.getId().toString());
            startActivity(intent);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_list);

        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setHomeButtonEnabled(true);
            supportActionBar.setDisplayHomeAsUpEnabled(true);
        }

        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(refreshListener);

        RecyclerView viewById = findViewById(R.id.listview);
        viewById.setLayoutManager(new LinearLayoutManager(this));
        adapter = new UserListAdapter(R.layout.fragment_user_list_item, USER_LIST);
        viewById.setAdapter(adapter);
        adapter.openLoadAnimation();
        adapter.setOnItemClickListener(onItemClickListener);

        rs = RenderScript.create(this);
        userModelAdapter = FlowManager.getModelAdapter(User.class);

    }

    @Override
    protected void onStart() {
        super.onStart();

        FileUtils.createOrExistsDir(USER_HEADER_DIR);

        refreshLayout.startRefresh();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        if (item.getItemId() == R.id.action_settings) {
            DWImages.getImages(this, DWImages.ACTION_ALBUM, 6);
        }

        if (item.getItemId() == R.id.delete_all) {
            SQLite.delete().from(User.class).execute();
            adapter.notifyDataSetChanged();
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        DWImages.parserResult(requestCode, data, new DWImages.GetImagesCallback() {
            @Override
            public void onResult(final List<String> images) {
                if (images.isEmpty()) return;

                final ACProgressFlower dialog = new ACProgressFlower.Builder(UserListActivity.this).direction(ACProgressConstant.DIRECT_CLOCKWISE).themeColor(Color.WHITE).text("正在重新加载人脸").fadeColor(Color.DKGRAY).build();
                dialog.show();

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < images.size(); i++) {
                            Bitmap bitmap = ImageUtils.getBitmap(images.get(i));
                            if (bitmap == null) continue;
                            try {
                                Nv21Image nv21Image = Nv21Image.bitmapToNV21(rs, bitmap);
                                ArcSdkEngine.getInstance().detection(nv21Image.nv21ByteArray, nv21Image.width, nv21Image.height, FACE_RECT_LIST);
                                if (FACE_RECT_LIST.isEmpty()) continue;

                                for (Rect rect : FACE_RECT_LIST) {
                                    Bitmap bmp_header = Bitmap.createBitmap(bitmap, rect.left, rect.top, (rect.right - rect.left), (rect.bottom - rect.top));
                                    String file_header = USER_HEADER_DIR + System.currentTimeMillis() + ".jpg";
                                    ImageUtils.save(bmp_header, file_header, Bitmap.CompressFormat.JPEG, true);

                                    User user = new User(UUID.randomUUID(), "无姓名", "无编号", file_header, new Date());
                                    userModelAdapter.insert(user);

                                    AFR_FSDKFace feature = ArcSdkEngine.getInstance().feature(nv21Image.nv21ByteArray, nv21Image.width, nv21Image.height, rect, 0);
                                    FileIOUtils.writeFileFromBytesByStream(file_header + ".data", feature.getFeatureData());
                                    ArcSdkEngine.getInstance().addToCache(user.getId().toString(), feature);
                                }


                            } catch (Exception e) {
                                Logger.e(e, "添加用户失败");
                                SnackbarUtils.with(refreshLayout).setMessage(e.getMessage()).setBottomMargin(1).showError();
                            } finally {
                                bitmap.recycle();
                            }
                        }
                        dialog.dismiss();
                    }
                }, 500);
            }
        });
    }

    private void reload(int i) {
        if (i == 0) {
            USER_LIST.clear();
        }
        List<User> users = SQLite.select().from(User.class).offset(i).limit(30).queryList();
        Logger.d("加载 %d -> %d = %d ", i, 30, users.size());
        USER_LIST.addAll(users);
        adapter.notifyDataSetChanged();

        if (users.size() == 0) {
            SnackbarUtils.with(refreshLayout).setMessage("没有更多了").setBottomMargin(1).showWarning();
        }
    }

}
